const express =require("express")
const router= express.Router();
const multer=require("multer");
const path=require("path")

function randomNum(min,max){
  return parseInt(Math.random() *max-min +min) 
}
//创建一个存储对象
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null,'./public/upload')
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + randomNum(10000000000,1000000000000)+path.extname(file.originalname) )
  }
})
 
const upload=multer({
  fileFilter:function(req,file,cb){
      //得到文件的后缀名
    
      const ext= path.extname(file.originalname).toLowerCase();  //转化成小写
      const expects =[".jpg",".png",".gif",".tiff",".bmp"]
      if(expects.includes(ext)){
        cb(null,true)
      }else{
        cb(new Error("文件类型不允许"))
      }
  },
  limits:{
    fieldSize: 500 * 1024
  },
  storage: storage
}).array("imgfile")


router.post("/",(req,res)=>{
  upload(req, res, function (err) {
    if (err) {
      // 发生错误
      res.send({
        code:1,
        message:err.message
      })
    } else if (err) {
      // 发生错误
    }
   
    res.send({
      code:0,
      message:"",
      data:req.files.map(item => "../../upload/" +item.filename)
    })
    // 一切都好
  })
})


module.exports=router;